<template>
	<el-upload class='img-uploader'
	    action='#'
	    :show-file-list='false'
	    :before-upload='onUploadImg'>
	    <img v-if='img' :src='img' class='img' :style='{width: width+"px",height:height+"px"}'/>
	    <i v-else class='el-icon-plus img-uploader-icon'></i>
	    <div class="el-upload__text">请上传宽高比为{{widthScale}}:{{heightScale}},大小为{{minSize}}~{{maxSize}}M的图片</div>
	</el-upload>
</template>

<script>
	import {cbs} from '../../../config/settings.js';
	import {mapGetters} from 'vuex';

	module.exports = {
		data() {
			return {
				img: this.imgUrl,
				width: this.imgWidth || this.widthScale * 20,
				height: this.imgHeight || this.heightScale * 20
			}
		},
		props: {
			widthScale: {
				type: Number,
				default: 16
			},
			heightScale: {
				type: Number,
				default: 9
			},
			minSize: {
				type: Number,
				default: 1
			},
			maxSize: {
				type: Number,
				default: 2
			},
			imgWidth: {
				type: Number
			},
			imgHeight: {
				type: Number
			}
		},
		methods: {
			/**
		     * 获取七牛token
		     */
			onGetQiNiuToken(fn) {
	            this.hasUpload = true;
	            let data = {
	                waterStoreId: this.waterId,
	                token: this.token
	            },
	                token = '';
	            this.$$api_image_getQiniuToken(data, res => {
	                if(res.event === 0) {
	                    token = res.obj;
	                }else {
	                	this.img = '';
	                }
	                fn && fn(token);
	            }, {
	            	errFn: err => {
                    	this.img = '';
                    }
	            })
	        },
	        /**
		     * 上传图片
		     */
	        onUploadImg(file) {
	        	// 读取图片信息
	        	let reader = new FileReader();

	        	reader.onload = e => {
		        	this.checkSize(reader.result).then(() => {
		        		let size = file.size / 1024 / 1024;
		        		if(size >= this.minSize && size <= this.maxSize) {
			        		this.changeImgUrl(reader.result);

				            this.onGetQiNiuToken((token) => {
				                let data = new FormData();
				                data.append('file', file);
				                data.append('token', token);
				  
				                this.$$api_image_uploadQiniuFile(data, res => {
				                    cbs.submitSuccess.call(this, '上传成功');
				                    this.$emit('getUrl', res.key)
				                }, {
				                    host: '//up-z2.qiniu.com/',
				                    headers: {
				                      'Content-Type': 'multipart/form-data'
				                    },
				                    errFn: err => {
				                    	this.img = '';
				                    }
				                })
				            })
		        		}else {
		        			cbs.submitError.call(this, `图片大小需为${this.minSize}~${this.maxSize}M`);
		        		}
		        	})
		        	.catch(err => {
		        		cbs.submitError.call(this, err);
		        	})
	        	}
	        	reader.readAsDataURL(file);

	        },
	        /**
		     * 检查图片大小
		     */
	        checkSize(data) {
	        	return new Promise((resolve, reject) => {
		        	let img = new Image();

		        	img.src = data;
		        	img.onload = () => {
		        		if(img.width / img.height === this.widthScale / this.heightScale) {
		        			resolve();
		        		}else {
		        			reject(`图片宽高比需为${this.widthScale}:${this.heightScale}`);
		        		}
		        	}
	        	})
	        },
	        /**
		     * 清除图片
		     */
	        clearImg() {
	        	this.img = '';
	        },
	        /**
		     * 改变图片
		     */
	        changeImgUrl(url='') {
	        	this.img = url;
	        }
		},
		computed: mapGetters({
			token: 'getToken',
			waterId: 'getUserId'
		}),
		mounted() {
			let height = this.heightScale * 20,
				width = this.widthScale * 20;

			$('.img-uploader').css({
				'width': `${this.imgWidth + 2 || width + 2}px`,
				'height': `${this.imgHeight + 2 || height + 2}px`
			});
			$('.img-uploader-icon').css({
				'width': `${this.imgWidth || width}px`,
				'height': `${this.imgHeight || height}px`
			})
		}
	}
</script>

<style scoped lang='less'>

	.img-uploader {
	    position: relative;
	    display: inline-block;
	    border: 1px solid #c0ccda;
	    border-radius: 6px;
	    background: #f9fafc;
	    cursor: pointer;
	}
	.img-uploader:hover {
	    border-color: #20a0ff;
	}
	.img-uploader-icon {
	    font-size: 28px;
	    color: #c0ccda;
	    line-height: 178px;
	    text-align: center;
	}
	.img {
	    display: block;
	}
	.el-icon-plus:before {
		font-size: 48px;
	}
	.el-upload__text {
		color: red;
		font-size: 12px;
		line-height: 18px;
	}
</style>